<template>
  <x-search>
    <template #search>
      <p>
        权限名称
        <a-input
          v-model:value="searchParams.name"
          placeholder="请输入权限名称"
          style="width: 150px"
        />
      </p>
      <p style="margin-left: 10px">
        权限标识
        <a-input
          v-model:value="searchParams.rolecode"
          placeholder="请输入权限标识"
          style="width: 150px"
        />
      </p>
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="fetchPermissions"
        >搜索</a-button
      >
      <a-button style="margin-left: 10px" @click="resetSearch">重置</a-button>
    </template>
    <template #operate>
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="openAddModal = true"
        v-checkpermission="'permiss_add'"
      >
        <plus-outlined style="margin-right: 0" />
        新增权限
      </a-button>
    </template>
  </x-search>

  <!-- 新增权限对话框 -->
  <a-modal
    v-model:open="openAddModal"
    title="新增权限"
    @ok="handleAddPermission"
    v-checkpermission="'permiss_list'"
  >
    <a-form
      ref="formRef"
      :model="newPermission"
      :rules="formRules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 13 }"
    >
      <a-form-item label="权限名称" name="name">
        <a-input
          v-model:value="newPermission.name"
          placeholder="请输入权限名称"
        />
      </a-form-item>
      <a-form-item label="权限描述" name="description">
        <a-input
          v-model:value="newPermission.description"
          placeholder="请输入权限描述"
        />
      </a-form-item>
      <a-form-item label="权限标识" name="permission_code">
        <a-input
          v-model:value="newPermission.permission_code"
          placeholder="请输入权限标识"
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 权限列表表格 -->
  <a-table
    :dataSource="dataSource"
    :columns="columns"
    :row-selection="{
      selectedRowKeys: tableState.selectedRowKeys,
      onChange: onSelectChange,
    }"
    :pagination="{
      pageSize: tableState.pageSize,
      total: tableState.total,
      current: tableState.current,
      showSizeChanger: true,
      pageSizeOptions: ['5', '10', '20', '50'],
      showTotal: (total:number) => `共 ${total} 条`,
    }"
    @change="handleTableChange"
    :scroll="{ y: 600 }"
    :loading="tableState.loading"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-button
          type="link"
          @click="showEditModal(record)"
          v-checkpermission="'permiss_edit'"
        >
          <EditOutlined /> 编辑
        </a-button>
        <a-button
          type="link"
          danger
          @click="deletePermission(record.id)"
          v-checkpermission="'permiss_delete'"
        >
          <DeleteOutlined /> 删除
        </a-button>
        <a-button
          type="link"
          danger
          style="width: 100px; color: #1890ff"
          @click="showPermissionModal(record.id)"
          v-checkpermission="'permiss_set'"
        >
          <EditOutlined style="margin-right: 0" />
          权限分配
        </a-button>
      </template>
    </template>
  </a-table>

  <!-- 编辑权限对话框 -->
  <a-modal
    v-model:open="openEditModal"
    title="修改权限"
    @ok="handleEditPermission"
  >
    <a-form
      ref="editFormRef"
      :model="editingPermission"
      :rules="formRules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 13 }"
    >
      <a-form-item label="权限名称" name="name">
        <a-input v-model:value="editingPermission.name" />
      </a-form-item>
      <a-form-item label="权限标识" name="permission_code">
        <a-input v-model:value="editingPermission.permission_code" />
      </a-form-item>
      <a-form-item label="权限描述" name="description">
        <a-input v-model:value="editingPermission.description" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 权限设置弹窗 -->
  <a-modal
      v-model:open="permissionModalVisible"
      title="权限设置"
      @ok="handlePermissionSubmit"
    >
      <a-cascader
        v-model:value="selectedPermissions"
        style="width: 100%"
        multiple
        max-tag-count="responsive"
        :options="permissionOptions"
        placeholder="请选择权限"
      />
    </a-modal>
</template>

<script lang="ts" setup>
import XSearch from "../components/XSearch.vue";
import { ref, reactive, onMounted, createVNode } from "vue";
import http from "../http/http";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import type { Rule } from "ant-design-vue/es/form";
import type { TablePaginationConfig } from "ant-design-vue/es/table";
import dayjs from "dayjs";
import { useStore } from "vuex";
import type { CascaderProps } from "ant-design-vue";
const store = useStore();
// 创建一个自定义指令，来统一处理权限存在与否
const userPermiss_vuex = store.state.userPermiss;
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    // console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 类型定义
interface Permission {
  id: number;
  name: string;
  description: string;
  permission_code: string;
  created_at: string;
  father?: number;
  sign?: string;
  type?: number;
  router_url?: string;
  component_url?: string;
  icon?: string;
  sort?: number;
}

interface FormState {
  name: string;
  father?: number | string;
  sign?: string;
  type?: number;
  description?: string;
  permission_code?: string;
  router_url?: string;
  component_url?: string;
  icon?: string;
  sort?: number;
}

interface TableState {
  selectedRowKeys: number[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}

// 组件状态
const searchParams = reactive({
  name: "",
  rolecode: "",
});

const tableState = reactive<TableState>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 5,
  total: 100,
  current: 1,
});

const dataSource = ref<Permission[]>([]);

// 表单相关
const formRules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入权限名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  permission_code: [
    { required: true, message: "请输入权限标识", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
};

// 新增权限
const openAddModal = ref(false);
const formRef = ref();
const newPermission = reactive<FormState>({
  name: "",
  description: "",
  permission_code: "",
});

// 编辑权限
const openEditModal = ref(false);
const editFormRef = ref();
const editingPermission = reactive<Permission>({
  id: 0,
  name: "",
  description: "",
  permission_code: "",
  created_at: "",
});

// 权限设置相关
const permissionModalVisible = ref(false);
const selectedPermissions = ref([]);
let permissionOptions: CascaderProps["options"] = [];
// const permissionOptions = ref([]);
const currentRoleId = ref(0);
// 全部角色的接口
const all_permission = async () => {
  try {
    const results = await http.get("/api/roles/all");
    console.log(results);
    permissionOptions = results.data.results.map((item: any) => {
      const options_filter = {
        value: item.id,
        label: item.name,
      };
      return options_filter;
    });
    console.log("permissionOptions.value", permissionOptions);
  } catch (error) {
    console.error("权限获取失败:", error);
    message.error("权限获取失败");
  }
};
const showPermissionModal = async (id: number) => {
  console.log(id)
  await all_permission();
  currentRoleId.value = id;
  permissionModalVisible.value = true;
  try {
    const results = await http.get("/api/permissions/roles_get", {
      params: {
        permiss_id: id,
      },
    });
    console.log(results);
    selectedPermissions.value = results.data.results.map((item: any) => [item.id]);

    // selectedPermissions.value = all_permission
    // permissionOptions.value = all_permission_option
    console.log(selectedPermissions.value);
  } catch (error) {
    console.error("权限获取失败:", error);
    message.error("权限获取失败");
  }
};

const handlePermissionSubmit = () => {
  console.log(selectedPermissions.value)
  if (selectedPermissions.value.length === 0) {
    message.warning("请至少选择一种权限");
    return;
  }

  const permissionIds = selectedPermissions.value
    .map((item) => item[0])
    .join(",");
  console.log(permissionIds)
  http
    .get("/api/permissions/roles_set", {
      params: {
        permiss_id:currentRoleId.value,
        role_ids: permissionIds
        // id: currentRoleId.value,
        // expression_ids: permissionIds,
      },
    })
    .then((response: any) => {
      message.success("权限设置成功");
      permissionModalVisible.value = false;
    })
    .catch((error: any) => {
      console.error("权限设置失败:", error);
      message.error("权限设置失败");
    });
};

// 表格列定义
const columns = [
  { title: "权限名称", dataIndex: "name", key: "name", width: 120 },
  {
    title: "权限描述",
    dataIndex: "description",
    key: "description",
    width: 150,
  },
  {
    title: "权限标识",
    dataIndex: "permission_code",
    key: "permission_code",
    width: 120,
  },
  { title: "创建时间", dataIndex: "created_at", key: "created_at", width: 120 },
  { title: "操作", key: "action", width: 260 },
];

// 方法定义
const resetSearch = () => {
  searchParams.name = "";
  searchParams.rolecode = "";
  fetchPermissions();
};

const onSelectChange = (selectedRowKeys: number[]) => {
  tableState.selectedRowKeys = selectedRowKeys;
};

const handleTableChange = (pagination: TablePaginationConfig) => {
  tableState.pageSize = pagination.pageSize || 5;
  tableState.current = pagination.current || 1;
  fetchPermissions();
};

const fetchPermissions = async () => {
  try {
    tableState.loading = true;
    const response = await http.get("/api/permissions/list", {
      params: {
        name: searchParams.name,
        rolecode: searchParams.rolecode,
        page_size: tableState.pageSize,
        page: tableState.current,
      },
    });

    dataSource.value = response.data.results.permissions.map(
      (p: Permission) => ({
        ...p,
        key: p.id,
        created_at: dayjs(p.created_at).format("YYYY-MM-DD HH:mm:ss"),
      })
    );

    tableState.total = response.data.results.total;
  } catch (error) {
    console.error("获取权限列表失败:", error);
    message.error("获取权限列表失败");
  } finally {
    tableState.loading = false;
  }
};

const handleAddPermission = async () => {
  try {
    await formRef.value?.validate();

    const response = await http.post("/api/permissions/add", {
      name: newPermission.name,
      description: newPermission.description,
      permission_code: newPermission.permission_code,
    });

    message.success(response.data.msg);
    openAddModal.value = false;
    fetchPermissions();
    resetForm();
  } catch (error) {
    console.error("添加权限失败:", error);
  }
};

const resetForm = () => {
  Object.assign(newPermission, {
    name: "",
    description: "",
    permission_code: "",
  });
};

const showEditModal = async (scoped: any) => {
  openEditModal.value = true;
  console.log(scoped);
  Object.assign(editingPermission, {
    id: scoped.id,
    name: scoped.name,
    description: scoped.description,
    permission_code: scoped.permission_code,
    created_at: scoped.created_at,
  });
};

const handleEditPermission = async () => {
  try {
    await editFormRef.value?.validate();

    const response = await http.post("/api/permissions/set", {
      id: editingPermission.id,
      name: editingPermission.name,
      description: editingPermission.description,
      permission_code: editingPermission.permission_code,
    });

    message.success(response.data.msg);
    openEditModal.value = false;
    fetchPermissions();
  } catch (error) {
    console.error("更新权限失败:", error);
  }
};

const deletePermission = (id: number) => {
  Modal.confirm({
    title: "删除权限",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此权限吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.get("/api/permissions/delete_t", {
          params: { id },
        });
        message.success(response.data.msg);
        fetchPermissions();
      } catch (error) {
        console.error("删除权限失败:", error);
        message.error("删除权限失败");
      }
    },
  });
};

// 初始化
onMounted(() => {
  fetchPermissions();
});
</script>

<style scoped>
:deep(.ant-btn > .anticon + span),
:deep(.ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>